<template>
	<view class="container">
		<view class="header">
			<view class="title">执裁记录</view>
			<view class="filter-section">
				<view 
					class="filter-item" 
					v-for="(item, index) in filterOptions" 
					:key="index"
					:class="{'active': currentFilter === item.value}"
					@click="changeFilter(item.value)"
				>
					{{item.label}}
				</view>
			</view>
		</view>
		
		<!-- 执裁统计 -->
		<view class="statistics-section">
			<view class="stat-item">
				<text class="stat-value">{{statistics.total_matches || 0}}</text>
				<text class="stat-label">总执裁场次</text>
			</view>
			<view class="stat-item">
				<text class="stat-value">{{statistics.average_rating || 0}}</text>
				<text class="stat-label">平均评分</text>
			</view>
			<view class="stat-item">
				<text class="stat-value">{{(statistics.attendance_rate || 0).toFixed(1)}}</text>
				<text class="stat-label">出勤率(%)</text>
			</view>
		</view>
		
		<view class="empty-box" v-if="recordList.length === 0 && !isLoading">
			<image class="empty-icon" src="/static/images/empty-box.png" mode="aspectFit"></image>
			<text class="empty-text">
				{{currentFilter === 'all' ? '暂无执裁记录' : '暂无' + currentFilter + '执裁记录'}}
			</text>
			<text class="empty-hint">执裁记录会在管理员确认选派后自动生成</text>
		</view>
		
		<!-- 加载状态 -->
		<view class="loading-box" v-if="isLoading && recordList.length === 0">
			<text class="loading-text">加载中...</text>
		</view>
		
		<scroll-view scroll-y class="record-list" v-else>
			<!-- 执裁记录列表 -->
			<view class="record-item" v-for="(item, index) in recordList" :key="index" @click="openDetail(item)">
				<view class="item-content">
					<view class="item-title">{{item.match_title || '未知比赛'}}</view>
					<view class="item-teams" v-if="item.home_team || item.away_team">
						{{item.home_team || '主队'}} VS {{item.away_team || '客队'}}
					</view>
					<view class="item-meta">
						<text class="item-position" :class="[
							getPositionClass(item.position)
						]">{{getPositionText(item.position)}}</text>
						<text class="item-level">{{item.match_level}}</text>
						<text class="item-rating" v-if="item.execution_rating">{{item.execution_rating}}分</text>
						<text class="item-date">{{formatDate(item.match_date)}}</text>
					</view>
					<view class="item-venue" v-if="item.match_venue">
						<text class="venue-label">场地：</text>
						<text class="venue-text">{{item.match_venue}}</text>
					</view>
				</view>
				
							<view class="item-actions">
				<view class="status-badge" :class="[
					item.attendance_status === 'present' ? 'present' : '',
					item.attendance_status === 'absent' ? 'absent' : '',
					item.attendance_status === 'late' ? 'late' : ''
				]">
					{{getStatusText(item.attendance_status)}}
				</view>
			</view>
			</view>
		</scroll-view>
		
		<!-- 加载更多 -->
		<view class="load-more" v-if="recordList.length > 0 && hasMore">
			<text class="load-text" @click="loadMore">加载更多</text>
		</view>
		
		<!-- 底部提示 -->
		<view class="bottom-tip" v-if="recordList.length > 0 && !hasMore">
			<text class="tip-text">没有更多内容了</text>
		</view>
		
		<!-- 添加按钮 -->
		<view class="add-btn" @click="addRecord">
			<text class="add-icon">+</text>
		</view>
	</view>
</template>

<script>
	import { getToken } from '@/utils/tokenManager.js';
	
	export default {
		data() {
			return {
				filterOptions: [
					{label: '全部', value: 'all'},
					{label: '主裁判', value: '主裁判'},
					{label: '助理裁判', value: '助理裁判'},
					{label: '第四官员', value: '第四官员'},
					{label: '裁判监督', value: '裁判监督'}
				],
				currentFilter: 'all',
				recordList: [],
				statistics: {
					total_matches: 0,
					average_rating: 0,
					attendance_rate: 0
				},
				page: 1,
				pageSize: 10,
				hasMore: true,
				isLoading: false,
				isRefreshing: false // 添加刷新状态标识
			}
		},
		onLoad() {
			// 设置初始加载状态
			this.isLoading = true;
			
			// 获取执裁统计
			this.getRefereeStatistics();
			
			// 获取执裁记录列表
			this.getRefereeRecords();
		},
		onPullDownRefresh() {
			// 下拉刷新
			this.refreshRecords();
		},
		methods: {
			// 切换筛选条件
			changeFilter(value) {
				this.currentFilter = value;
				this.page = 1;
				this.recordList = [];
				this.hasMore = true;
				this.getRefereeRecords();
			},
			
			// 下拉刷新
			refreshRecords() {
				this.isRefreshing = true; // 设置刷新状态
				
				// 重置分页
				this.page = 1;
				this.recordList = [];
				this.hasMore = true;
				
				// 同时刷新统计和记录
				Promise.all([
					this.getRefereeStatisticsPromise(),
					this.getRefereeRecordsPromise(false)
				]).then(() => {
					uni.showToast({
						title: '刷新成功',
						icon: 'success',
						duration: 1500
					});
				}).catch((error) => {
					console.error('刷新执裁记录失败', error);
					uni.showToast({
						title: '刷新失败，请重试',
						icon: 'none',
						duration: 2000
					});
				}).finally(() => {
					this.isRefreshing = false; // 重置刷新状态
					// 停止下拉刷新动画
					uni.stopPullDownRefresh();
				});
			},
			
			// 获取执裁统计（Promise版本）
			async getRefereeStatisticsPromise() {
				try {
					const token = getToken();
					
					if (!token) {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						});
						return null;
					}
					
					const refereeRecordService = uniCloud.importObject('referee-record-service');
					const res = await refereeRecordService.getRefereeStatistics({
						token: token,
						year: new Date().getFullYear()
					});
					
					if (res && res.code === 0) {
						this.statistics = res.data || {
							total_matches: 0,
							average_rating: 0,
							attendance_rate: 0
						};
						return res.data;
					} else {
						console.error('获取执裁统计失败:', res ? res.message : '未知错误');
						const errorMsg = res ? res.message : '获取统计数据失败';
						
						// 只在非刷新操作时显示错误提示
						if (!this.isRefreshing) {
							uni.showToast({
								title: errorMsg,
								icon: 'none'
							});
						}
						return null;
					}
				} catch (err) {
					console.error('获取执裁统计失败', err);
					
					// 只在非刷新操作时显示错误提示
					if (!this.isRefreshing) {
						uni.showToast({
							title: '网络异常，请重试',
							icon: 'none'
						});
					}
					throw err;
				}
			},
			
			// 获取执裁记录（Promise版本）
			async getRefereeRecordsPromise(loadMore = false) {
				try {
					const token = getToken();
					
					if (!token) {
						if (!this.isRefreshing) {
							uni.showToast({
								title: '请先登录',
								icon: 'none'
							});
						}
						return [];
					}
					
					const refereeRecordService = uniCloud.importObject('referee-record-service');
					const res = await refereeRecordService.getRefereeRecords({
						token: token,
						page: this.page,
						pageSize: this.pageSize,
						position: this.currentFilter === 'all' ? '' : this.currentFilter
					});
					
					if (res && res.code === 0) {
						const data = res.data;
						
						const processedRecords = (data.list || []).map(item => {
							return {
								...item,
								match_title: item.match_title || '未知比赛',
								// 确保出勤状态的正确映射
								attendance_status: this.normalizeAttendanceStatus(item.attendance_status)
							};
						});
						
						if (loadMore) {
							this.recordList = [...this.recordList, ...processedRecords];
						} else {
							this.recordList = processedRecords;
						}
						
						// 更新分页信息
						this.hasMore = processedRecords.length >= this.pageSize;
						
						return processedRecords;
					} else {
						console.error('获取执裁记录失败:', res ? res.message : '未知错误');
						const errorMsg = res ? res.message : '获取执裁记录失败';
						
						// 只在非刷新和非加载更多时显示错误提示
						if (!this.isRefreshing && !loadMore) {
							uni.showToast({
								title: errorMsg,
								icon: 'none'
							});
						}
						
						if (!loadMore) {
							this.recordList = [];
						}
						return [];
					}
				} catch (err) {
					console.error('获取执裁记录失败', err);
					
					// 只在非刷新和非加载更多时显示错误提示
					if (!this.isRefreshing && !loadMore) {
						uni.showToast({
							title: '网络异常，请重试',
							icon: 'none'
						});
					}
					
					if (!loadMore) {
						this.recordList = [];
					}
					throw err;
				}
			},
			
			// 获取执裁统计
			getRefereeStatistics() {
				this.getRefereeStatisticsPromise().catch(() => {
					// 错误处理已在Promise版本中完成
				});
			},
			
			// 获取执裁记录
			getRefereeRecords() {
				this.getRefereeRecordsPromise().finally(() => {
					this.isLoading = false;
				}).catch(() => {
					// 错误处理已在Promise版本中完成
				});
			},
			
			// 加载更多
			loadMore() {
				if (this.isLoading || !this.hasMore) {
					return;
				}
				
				this.isLoading = true;
				this.page++;
				
				this.getRefereeRecordsPromise(true).finally(() => {
					this.isLoading = false;
				});
			},
			
			// 打开详情
			openDetail(item) {
				uni.navigateTo({
					url: `/packageMy/my/match-record-detail?id=${item._id}`
				});
			},
			
			// 添加记录
			addRecord() {
				uni.navigateTo({
					url: '/packageMy/my/add-match-record'
				});
			},
			
			// 格式化时间
			formatDate(timestamp) {
				if (!timestamp) return '';
				const date = new Date(timestamp);
				return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
			},
			

			
			// 标准化出勤状态
			normalizeAttendanceStatus(status) {
				const statusMap = {
					'正常出勤': 'present',
					'缺勤': 'absent',
					'迟到': 'late',
					'present': 'present',
					'absent': 'absent',
					'late': 'late'
				};
				return statusMap[status] || 'present'; // 默认为正常出勤
			},
			
			// 获取状态文本
			getStatusText(status) {
				const textMap = {
					'present': '正常出勤',
					'absent': '缺勤',
					'late': '迟到'
				};
				return textMap[status] || '正常出勤';
			},
			
			// 获取岗位中文文本
			getPositionText(position) {
				const positionMap = {
					'main_referee': '主裁判',
					'assistant_referee': '助理裁判',
					'fourth_official': '第四官员',
					'referee_supervisor': '裁判监督',
					'supervisor': '裁判监督',
					'边裁判': '助理裁判', // 兼容旧数据
					'主裁判': '主裁判',
					'助理裁判': '助理裁判',
					'第四官员': '第四官员',
					'裁判监督': '裁判监督'
				};
				return positionMap[position] || position || '未知职位';
			},
			
			// 获取岗位样式类
			getPositionClass(position) {
				const positionText = this.getPositionText(position);
				if (positionText === '主裁判') return 'main-referee';
				if (positionText === '助理裁判') return 'assistant-referee';
				if (positionText === '第四官员') return 'fourth-official';
				if (positionText === '裁判监督') return 'supervisor';
				return '';
			}
		}
	}
</script>

<style scoped>
	.container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}
	
	.header {
		background-color: #ffffff;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
	}
	
	.title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 30rpx;
		line-height: 1.2;
	}
	
	.filter-section {
		display: flex;
		flex-wrap: wrap;
		gap: 15rpx;
	}
	
	.filter-item {
		padding: 12rpx 24rpx;
		background-color: #f0f0f0;
		border-radius: 25rpx;
		font-size: 28rpx;
		color: #666666;
		transition: all 0.3s ease;
	}
	
	.filter-item.active {
		background-color: #1BAE76;
		color: #ffffff;
	}
	
	.statistics-section {
		display: flex;
		justify-content: space-around;
		background-color: #ffffff;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
	}
	
	.stat-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	
	.stat-value {
		font-size: 36rpx;
		font-weight: bold;
		color: #1BAE76;
		margin-bottom: 10rpx;
	}
	
	.stat-label {
		font-size: 24rpx;
		color: #999999;
	}
	
	.empty-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
		background-color: #ffffff;
		border-radius: 20rpx;
		margin: 40rpx 0;
	}
	
	.empty-icon {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
		opacity: 0.5;
	}
	
	.empty-text {
		color: #999999;
		font-size: 28rpx;
		margin-bottom: 10rpx;
	}
	
	.empty-hint {
		color: #cccccc;
		font-size: 24rpx;
		text-align: center;
	}
	
	.loading-box {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 100rpx 0;
		background-color: #ffffff;
		border-radius: 20rpx;
		margin: 40rpx 0;
	}
	
	.loading-text {
		color: #1BAE76;
		font-size: 28rpx;
	}
	
	.record-list {
		max-height: calc(100vh - 400rpx);
	}
	
	.record-item {
		background-color: #ffffff;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
	}
	
	.item-content {
		flex: 1;
	}
	
	.item-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 10rpx;
		line-height: 1.3;
	}
	
	.item-teams {
		font-size: 28rpx;
		color: #666666;
		margin-bottom: 15rpx;
	}
	
	.item-meta {
		display: flex;
		flex-wrap: wrap;
		gap: 10rpx;
		margin-bottom: 10rpx;
	}
	
	.item-position {
		padding: 4rpx 12rpx;
		border-radius: 15rpx;
		font-size: 24rpx;
		font-weight: bold;
	}
	
	.item-position.main-referee {
		background-color: #FF6B6B;
		color: #ffffff;
	}
	
	.item-position.assistant-referee {
		background-color: #4ECDC4;
		color: #ffffff;
	}
	
	.item-position.fourth-official {
		background-color: #45B7D1;
		color: #ffffff;
	}
	
	.item-position.supervisor {
		background-color: #96CEB4;
		color: #ffffff;
	}
	
	.item-level {
		padding: 4rpx 12rpx;
		background-color: #f0f0f0;
		border-radius: 15rpx;
		font-size: 24rpx;
		color: #666666;
	}
	
	.item-rating {
		padding: 4rpx 12rpx;
		background-color: #FFA726;
		color: #ffffff;
		border-radius: 15rpx;
		font-size: 24rpx;
		font-weight: bold;
	}
	
	.item-date {
		font-size: 24rpx;
		color: #999999;
	}
	
	.item-venue {
		font-size: 26rpx;
		color: #666666;
		margin-top: 10rpx;
	}
	
	.venue-label {
		color: #999999;
	}
	
	.venue-text {
		color: #666666;
	}
	
	.item-actions {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
	}
	
	.status-badge {
		padding: 8rpx 16rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
		font-weight: bold;
	}
	
	.status-badge.present {
		background-color: #4CAF50;
		color: #ffffff;
	}
	
	.status-badge.absent {
		background-color: #F44336;
		color: #ffffff;
	}
	
	.status-badge.late {
		background-color: #FF9800;
		color: #ffffff;
	}
	
	.load-more {
		text-align: center;
		padding: 30rpx;
		background-color: #ffffff;
		border-radius: 20rpx;
		margin: 20rpx 0;
	}
	
	.load-text {
		color: #1BAE76;
		font-size: 28rpx;
	}
	
	.bottom-tip {
		text-align: center;
		padding: 30rpx;
		color: #999999;
		font-size: 26rpx;
	}
	
	.add-btn {
		position: fixed;
		right: 40rpx;
		bottom: 100rpx;
		width: 100rpx;
		height: 100rpx;
		background-color: #1BAE76;
		border-radius: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 8rpx 30rpx rgba(27, 174, 118, 0.3);
		z-index: 999;
	}
	
	.add-icon {
		color: #ffffff;
		font-size: 50rpx;
		font-weight: bold;
	}
</style> 